package com.sxz.sbs.module.telephone;

import android.content.Intent;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.view.View;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.chad.library.adapter.base.listener.OnItemChildClickListener;
import com.chad.library.adapter.base.listener.OnItemClickListener;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.sxz.sbs.R;
import com.sxz.sbs.app.AppConstant;
import com.sxz.sbs.applibrary.state.StateLayout;
import com.sxz.sbs.base.BaseActivity;
import com.sxz.sbs.constant.IntentConstant;
import com.sxz.sbs.event.OperateTelSuccessEvent;
import com.sxz.sbs.http.retrofit.HttpParamMap;
import com.sxz.sbs.module.telephone.adapter.TelDepartmentAdapter;
import com.sxz.sbs.module.telephone.adapter.TelPersonnelAdapter;
import com.sxz.sbs.module.telephone.bean.TelBookBean;
import com.sxz.sbs.module.telephone.presenter.TelBookPresenter;
import com.sxz.sbs.module.telephone.view.TelBookView;
import com.sxz.sbs.util.FileUtils;
import com.sxz.sbs.widget.CommonTitle;
import com.sxz.sbs.widget.PhoneDialog;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * @author cz
 * @date 2018/1/5
 * 通话录
 */

public class TelBookActivity extends BaseActivity<TelBookPresenter> implements TelBookView {

    @BindView(R.id.rely_teldepartment)
    RecyclerView rvDepartment;
    @BindView(R.id.rely_telpersonnel)
    RecyclerView rvPersonnel;
    @BindView(R.id.tel_book_state)
    StateLayout stateLayout;
    @BindView(R.id.tel_book_position_state)
    StateLayout personnelState;
    private TelDepartmentAdapter telDepartmentAdapter;
    private TelPersonnelAdapter telPersonnelAdapter;
    private List<TelBookBean> departmentData = new ArrayList<>();
    private List<TelBookBean.ManagerListBean> personnelData = new ArrayList<>();

    @Override
    protected void init() {
        EventBus.getDefault().register(this);
        new CommonTitle.Builder(this).setTitle("通讯录").build().show();
        mPresenter.getTelBook(HttpParamMap.getParamMap());
        rvDepartment.setLayoutManager(new LinearLayoutManager(this));
        rvPersonnel.setLayoutManager(new LinearLayoutManager(this));
        telDepartmentAdapter = new TelDepartmentAdapter(departmentData);
        telPersonnelAdapter = new TelPersonnelAdapter(personnelData);
        rvDepartment.setAdapter(telDepartmentAdapter);
        rvPersonnel.setAdapter(telPersonnelAdapter);
        rvDepartment.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
                telDepartmentAdapter.setPressIndex(position);
                personnelData.clear();
                personnelState.showLoading();
                personnelData.addAll(departmentData.get(position).getManagerList());
                if (personnelData.size() <= 0) {
                    personnelState.showEmpty();
                } else {
                    personnelState.showContent();
                }
                telPersonnelAdapter.notifyDataSetChanged();
            }
        });
        stateLayout.setOnRetryListener(new StateLayout.OnRetryListener() {
            @Override
            public void onRetry(int state) {
                mPresenter.getTelBook(HttpParamMap.getParamMap());
            }
        });
        rvPersonnel.addOnItemTouchListener(new OnItemClickListener() {
            @Override
            public void onSimpleItemClick(BaseQuickAdapter adapter, View view, int position) {
                startActivity(new Intent(TelBookActivity.this,PersonageDetailsActivity.class)
                    .putExtra(IntentConstant.TEL_BOOK_DETAIL,personnelData.get(position)));
            }
        });
        rvPersonnel.addOnItemTouchListener(new OnItemChildClickListener() {
            @Override
            public void onSimpleItemChildClick(BaseQuickAdapter adapter, View view, int position) {
                PhoneDialog.callPhone(TelBookActivity.this,personnelData.get(position).getTxt_Phone());
            }
        });
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_telbook;
    }

    @Override
    protected TelBookPresenter createPresenter() {
        return new TelBookPresenter();
    }

    @OnClick({R.id.tv_tel_book_search,R.id.iv_title_more})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case R.id.tv_tel_book_search:
                startActivity(SearchTelBookActivity.class);
                break;
            case R.id.iv_title_more:
                break;
            default:
                break;
        }

    }

    @Override
    public void showError(int errorTag, String msg) {
        String data1 = null;
        try {
            data1 = FileUtils.readFile(this);
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (!TextUtils.isEmpty(data1)) {
            List<TelBookBean> data = new Gson().fromJson(data1.replaceAll("\\\\s*", ""), new TypeToken<ArrayList<TelBookBean>>(){}.getType());
            showList(data);
        } else {
            if (errorTag == AppConstant.NET_ERROR_CODE) {
                stateLayout.showNetwork();
            } else {
                stateLayout.showError();
            }
        }

    }


    @Override
    public void onGetTelBookSuccess(List<TelBookBean> data) {
        if (mIsLive) {
            String json  = new Gson().toJson(data);
            boolean isSuccess = FileUtils.createJsonFile(this,json);
            showList(data);
        }
    }

    /**
     * 展示
     * @param data
     */
    private void showList(List<TelBookBean> data) {
        if (data != null && data.size() > 0) {
            stateLayout.showContent();
            departmentData.clear();
            departmentData.addAll(data);
            telDepartmentAdapter.setPressIndex(0);
            personnelData.clear();
            personnelData.addAll(data.get(0).getManagerList());
            if (personnelData.size() <= 0) {
                personnelState.showEmpty();
            } else {
                personnelState.showContent();
            }
            telPersonnelAdapter.notifyDataSetChanged();
        } else {
            stateLayout.showEmpty();
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onOperateSuccessEvent(OperateTelSuccessEvent event) {
        mPresenter.getTelBook(HttpParamMap.getParamMap());
    }
    @Override
    protected void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }
}
